package com.kanshu.ksgb.fastread.doudou.module.reader.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdStyleBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.BaseAdListener;
import com.kanshu.ksgb.fastread.doudou.common.util.DiskLruCacheUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.NetUtils;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ChapterBean;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.SimpleChapterBean;
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.SettingManager;
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.ThemeManager;
import com.kanshu.ksgb.fastread.doudou.module.makemoney.utils.TimerManager;

import org.jetbrains.annotations.NotNull;


/**
 * Created by wcy on 18/4/2.
 */

public class AdBetweenChaptersLayout extends FrameLayout implements BaseAdListener {
    TextView mBookTitle;
    TextView mAuthor;
    TextView mNextChapterName;
    FrameLayout mAdContainer;
    LinearLayout mAdTipContainer;
    String mBookId;
    int mChapterIndex = -1;
    String mAuthorName = "";
    View mVipTipLayout;
    boolean mIsFirst = true;
    View mAdExpressTrans;
    Activity mActivity;

    public AdBetweenChaptersLayout(@NonNull Context context) {
        super(context);
        init(context);
    }

    public AdBetweenChaptersLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public AdBetweenChaptersLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        setWillNotDraw(true);
        if (context instanceof Activity) {
            mActivity = (Activity) context;
        }
        LayoutInflater.from(context).inflate(R.layout.ad_between_chapters_layout, this);
        mBookTitle = (TextView) findViewById(R.id.book_title);
        mAuthor = (TextView) findViewById(R.id.author);
        mNextChapterName = (TextView) findViewById(R.id.next_chapter);
        mAdContainer = (FrameLayout) findViewById(R.id.ad_container);
        mAdTipContainer = findViewById(R.id.ad_tip_container);
        mAdExpressTrans = findViewById(R.id.ad_banner_trans);
        findViewById(R.id.continue_read).setOnClickListener(view -> {
            DisplayUtils.gone(AdBetweenChaptersLayout.this);
            mAdContainer.removeAllViews();
            // 一章中的页数变化
            TimerManager.getInstance().saveReadedPageInfo();
            if (mAdContainer != null) {
                AdUtils.destroyAd(mAdContainer);
                mAdContainer.removeAllViews();
            }
        });
        initTheme();
    }

    public void refresh(String bookId, int chapter, int adType, boolean isNight) {
        if (!NetUtils.isNetworkAvailable(getContext())) {
            DisplayUtils.gone(this);
            return;
        }
        DisplayUtils.visible(this);
        mAdExpressTrans.setBackgroundColor(isNight ? Color.parseColor("#99000000") : Color.parseColor("#00000000"));
        if (!TextUtils.equals(bookId, mBookId)) {
            ChapterBean.BookInfoBean bean = DiskLruCacheUtils.get(bookId + "simple", ChapterBean.BookInfoBean.class);
            if (bean != null) {
                mAuthorName = bean.author_name;
            }
        }
//        if (mChapterIndex > chapter) {
//            return;
//        }
        mBookId = bookId;
        mChapterIndex = chapter;
        initTheme();
        SimpleChapterBean info = SettingManager.getInstance().getSimpleChapterInfo(mBookId, chapter);
        if (info != null) {
            // 显示布局
            DisplayUtils.visible(this);
            if (info.price > 0 && !SettingManager.getInstance().isFirstVipShow(mBookId)) {
                processVipTipShow(info.title);
            } else {
                // 第一次调用不显示这布局
                if (mIsFirst) {
                    mIsFirst = false;
                    DisplayUtils.gone(this);
                    return;
                }
                DisplayUtils.visible(mAdTipContainer);
                DisplayUtils.gone(mVipTipLayout);
                mBookTitle.setText(info.book_title);
                mAuthor.setText("作者:" + mAuthorName);
                mNextChapterName.setText("下一章:" + info.title);
                refreshAd(adType);
            }
        } else {
            DisplayUtils.gone(this);
        }
    }

    public void initTheme() {
        if (SettingManager.getInstance().isNight()) {
            setBackgroundResource(R.drawable.theme_night_bg);
            if (mBookTitle != null) {
                mBookTitle.setTextColor(Color.LTGRAY);
                mNextChapterName.setTextColor(Color.LTGRAY);
            }
        } else {
            ThemeManager.setReaderTheme(SettingManager.getInstance().getReadTheme(), this);
            if (mBookTitle != null) {
                mBookTitle.setTextColor(Color.BLACK);
                mNextChapterName.setTextColor(Color.BLACK);
            }
        }
    }

    private void processVipTipShow(String title) {
        DisplayUtils.gone(mAdTipContainer);
        SettingManager.getInstance().setFirstVipShow(mBookId, true);
        ViewStub stub = (ViewStub) findViewById(R.id.vip_stub);
        if (stub != null) {
            View view = stub.inflate();
            mVipTipLayout = view;
            if (SettingManager.getInstance().isNight()) {
                mVipTipLayout.setBackgroundResource(R.drawable.theme_night_bg);
            } else {
                ThemeManager.setReaderTheme(SettingManager.getInstance().getReadTheme(), mVipTipLayout);
            }
            TextView tv = (TextView) view.findViewById(R.id.chapter_title);
            tv.setText(title);
            view.findViewById(R.id.continue_read).setOnClickListener(view1 -> {
                DisplayUtils.gone(AdBetweenChaptersLayout.this);
                // 一章中的页数变化
                TimerManager.getInstance().saveReadedPageInfo();
                if (mAdContainer != null) {
                    AdUtils.destroyAd(mAdContainer);
                    mAdContainer.removeAllViews();
                }
            });
            setOnClickListener(null);
        }
    }

    private void refreshAd(int adType) {
        if (mActivity != null) {
            AdUtils.fetchAdUtil(mActivity, mAdContainer, null, adType, AdStyleBean.IMAGE_TEXT_STYLE, 0, this);
        }
        setOnClickListener(view -> {
            DisplayUtils.gone(AdBetweenChaptersLayout.this);
            // 一章中的页数变化
            TimerManager.getInstance().saveReadedPageInfo();
            if (mAdContainer != null) {
                AdUtils.destroyAd(mAdContainer);
                mAdContainer.removeAllViews();
            }
        });
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        setBackgroundResource(0);
        if (mAdContainer != null) {
            AdUtils.destroyAd(mAdContainer);
            mAdContainer.removeAllViews();
        }
    }

    public void resetIsFirst() {
        mIsFirst = true;
    }

    @Override
    public void onAdLoadSucceeded(@org.jetbrains.annotations.Nullable View view) {
    }

    @Override
    public void onAdLoadFailed() {
    }

    @Override
    public void onAdClicked() {
    }

    @Override
    public void onADClosed() {
    }

    @Override
    public void onBackAd(@NotNull Object ad) {
    }

}
